<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>节日管理</title>
		<link rel="stylesheet" href="../layui/css/layui.css">
		<link rel="stylesheet" href="../css/index.css">
		<style>
			.festival-container {
				padding: 20px;
			}

			.festival-table {
				width: 100%;
				border-collapse: collapse;
				margin-top: 20px;
			}

			.festival-table th,
			.festival-table td {
				border: 1px solid #ccc;
				padding: 10px;
				text-align: center;
			}

			.festival-table th {
				background-color: #d8d8d9;
				color: black;
				font-weight: bold;
			}

			.festival-table tr:nth-child(even) {
				background-color: #f9f9f9;
			}

			.festival-table tr:hover {
				background-color: #f1f1f1;
			}

			.festival-actions {
				display: flex;
				justify-content: center;
				gap: 5px;
			}

			.festival-form-item {
				margin-bottom: 15px;
			}

			.layui-card-header {
				font-size: 22px;
				color: #333;
				margin-bottom: 20px;
				font-weight: 600;
			}

			/* 列宽分配 */
			.festival-table th:nth-child(1),
			.festival-table td:nth-child(1) {
				width: 10%;
			}

			.festival-table th:nth-child(2),
			.festival-table td:nth-child(2) {
				width: 20%;
			}

			.festival-table th:nth-child(3),
			.festival-table td:nth-child(3) {
				width: 15%;
			}

			.festival-table th:nth-child(4),
			.festival-table td:nth-child(4) {
				width: 15%;
			}

			.festival-table th:nth-child(5),
			.festival-table td:nth-child(5) {
				width: 20%;
			}

			.festival-table th:nth-child(6),
			.festival-table td:nth-child(6) {
				width: 10%;
			}

			/* 按钮样式 */
			#addFestival {
				background-color: #FF1493;
				color: white;
			}

			.festival-icon-preview {
				width: 100px;
				height: 60px;
				object-fit: cover;
				border: 1px solid #eee;
				margin-top: 10px;
			}

			/* 搜索框样式 */
			.search-container {
				display: flex;
				margin-bottom: 20px;
			}

			.search-input {
				flex: 1;
				margin-right: 10px;
			}

			/* 操作按钮样式 */
			.action-btn {
				padding: 0 8px;
				height: 28px;
				line-height: 28px;
				font-size: 12px;
				min-width: 60px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				background: none;
				border: 1px solid #d8d8d9;
				color: #333;
				cursor: pointer;
			}

			.action-btn:hover {
				background-color: #f1f1f1;
			}

			/* 优惠券标签样式 */
			.discount-tag {
				display: inline-block;
				padding: 2px 8px;
				background-color: #f0f0f0;
				border-radius: 4px;
				font-size: 12px;
				margin-right: 5px;
			}
		</style>
	</head>
	<body>
		<div class="festival-container">
			<div class="layui-row layui-col-space15">
				<div class="layui-col-md12">
					<div class="layui-card">
						<div class="layui-card-header">节日管理</div>
						<div class="layui-card-body">
							<div class="search-container">
								<div class="layui-input-block search-input">
									<input type="text" id="searchInput" placeholder="请输入节日名称搜索" class="layui-input">
								</div>
								<button class="layui-btn layui-btn-primary" id="searchBtn">
									<i class="layui-icon">&#xe615;</i> 搜索
								</button>
								<button class="layui-btn" id="addFestival">
									<i class="layui-icon">&#xe654;</i> 新增节日
								</button>
								<button class="layui-btn layui-btn-primary" id="refreshBtn">
									<i class="layui-icon">&#x1002;</i> 刷新
								</button>
							</div>
						</div>
					</div>
				</div>

				<!-- 节日列表表格 -->
				<table class="festival-table" id="festivalTable">
					<thead>
						<tr>
							<th>ID</th>
							<th>节日名称</th>
							<th>开始时间</th>
							<th>结束时间</th>
							<th>节日图片</th>
							<th>关联优惠券</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						<!-- 动态内容将通过JS填充 -->
					</tbody>
				</table>

				<!-- 分页控件 -->
				<div id="pagination" style="text-align: center; margin-top: 20px;"></div>
			</div>
		</div>

		<!-- 新增/编辑节日弹窗 -->
		<div id="festivalDialog" style="display: none; padding: 20px;">
			<form class="layui-form" lay-filter="festivalForm">
				<input type="hidden" name="festivalid">
				<div class="festival-form-item">
					<label class="layui-form-label">节日名称</label>
					<div class="layui-input-block">
						<input type="text" name="festivalname" required lay-verify="required" placeholder="请输入节日名称"
							autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="festival-form-item">
					<label class="layui-form-label">开始时间</label>
					<div class="layui-input-block">
						<input type="text" name="festivalstart" class="layui-input" id="startTime"
							placeholder="请选择开始时间">
					</div>
				</div>
				<div class="festival-form-item">
					<label class="layui-form-label">结束时间</label>
					<div class="layui-input-block">
						<input type="text" name="festivalend" class="layui-input" id="endTime" placeholder="请选择结束时间">
					</div>
				</div>
				<div class="festival-form-item">
					<label class="layui-form-label">节日图片</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn" id="uploadBtn">
							<i class="layui-icon">&#xe67c;</i>上传图片
						</button>
						<div class="layui-upload-list">
							<img class="festival-icon-preview" id="previewImg" style="display: none;">
						</div>
					</div>
				</div>
				<div class="festival-form-item">
					<label class="layui-form-label">关联优惠券</label>
					<div class="layui-input-block">
						<!-- 当前优惠券信息展示区 -->
						<div id="discountInfo" style="display: none;"></div>

						<!-- 优惠券选择下拉框 -->
						<select name="discountid" lay-verify="" lay-search id="discountSelect">
							<option value="">请选择优惠券</option>
							<!-- 动态选项将在这里显示 -->
						</select>
					</div>
				</div>
				<div class="festival-form-item">
					<label class="layui-form-label">祝福语</label>
					<div class="layui-input-block">
						<textarea name="bless" placeholder="请输入节日祝福语" class="layui-textarea"></textarea>
					</div>
				</div>
			</form>
		</div>

		<script src="../js/jquery3.5.1.js"></script>
		<script src="../layui/layui.js"></script>
		<script>
			layui.use(['form', 'layer', 'upload', 'laydate', 'laypage'], function() {
				var form = layui.form;
				var layer = layui.layer;
				var upload = layui.upload;
				var laydate = layui.laydate;
				var laypage = layui.laypage;
				var $ = layui.$;

				// 全局变量
				var currentPage = 1;
				var pageSize = 10;
				var searchKeyword = '';
				var baseUrl = 'http://localhost:8887/festival';
				// 新增：存储当前编辑的活动ID和优惠券ID
				var currentEditFestivalId = null;
				var currentDiscountId = null;

				// 上传状态
				var uploadStatus = {
					isUploaded: false,
					imageUrl: ''
				};

				// 初始化日期选择器
				laydate.render({
					elem: '#startTime',
					type: 'date',
					format: 'yyyy-MM-dd'
				});

				laydate.render({
					elem: '#endTime',
					type: 'date',
					format: 'yyyy-MM-dd'
				});

				// 初始化上传组件
				upload.render({
					elem: '#uploadBtn',
					url: 'http://localhost:8887/upload/categoryImage',
					size: 10240, // 10MB限制
					accept: 'images',
					acceptMime: 'image/*',
					done: function(res) {
						if (res.code === 200) {
							$('#previewImg').attr('src', res.data.url).show();
							uploadStatus.imageUrl = res.data.url;
							uploadStatus.isUploaded = true;
							layer.msg('图片上传成功', {
								icon: 1
							});
						} else {
							uploadStatus.isUploaded = false;
							layer.msg(res.msgerr || '上传失败', {
								icon: 2
							});
						}
					},
					error: function() {
						layer.msg('上传失败，请稍后重试', {
							icon: 2
						});
					}
				});
				// 显示优惠券关联区域
				function showDiscountArea() {
					// 获取整个div元素
					const discountArea = document.querySelector('.festival-form-item:nth-child(6)');
					// 或通过更精确的选择器（如果有多个同类元素）
					// const discountArea = document.querySelector('div:has(#discountSelect)');

					// 设置display为block（或原有的默认显示值）
					discountArea.style.display = 'block';
				}

				// 隐藏优惠券关联区域
				function hideDiscountArea() {
					const discountArea = document.querySelector('.festival-form-item:nth-child(6)');
					// 设置display为none，完全隐藏且不占空间
					discountArea.style.display = 'none';
				}
				// 加载优惠券选项：新增参数用于编辑时选中当前优惠券
				function loadDiscountOptions(selectId) {
					$.ajax({
						url: baseUrl + '/selectAvailableDiscounts',
						type: 'GET',
						success: function(res) {
							console.log("获取优惠券信息：");
							console.log(res);

							if (res.code !== 200) {
								layer.msg(res.msgerr || '加载优惠券失败', {
									icon: 2
								});
								return;
							}

							// 处理返回数据格式
							var discountList = [];
							if (Array.isArray(res.data.discountList)) {
								discountList = res.data.discountList;
							} else if (res.data.discountList && typeof res.data.discountList === 'object') {
								discountList = [res.data.discountList];
								console.warn('后端返回单个对象');
							} else {
								console.warn('后端返回非数组数据');
							}

							// 生成下拉选项
							var options = '<option value="">请选择优惠券</option>';
							if (discountList.length === 0) {
								options += '<option value="" disabled>暂无可用优惠券</option>';
							} else {
								discountList.forEach(function(discount) {
									var id = discount.discountid || discount.value || '';
									var name = discount.discountname || discount.label || '未知优惠券';
									var desc = discount.description || '';
									// 编辑时选中当前优惠券
									var selected = selectId && id == selectId ? 'selected' : '';
									options +=
										`<option value="${id}" ${selected}>${name}${desc ? ' (' + desc + ')' : ''}</option>`;
								});
							}

							$('#discountSelect').html(options);
							form.render('select'); // 重新渲染下拉框使选中生效
						},
						error: function() {
							layer.msg('加载优惠券失败', {
								icon: 2
							});
						}
					});
				}

				// 加载节日列表
				function loadFestivals(page, keyword) {
					var url = baseUrl + '/selectFestivalPageEnd';
					var params = {
						page: page || currentPage,
						pageSize: pageSize
					};

					if (keyword && keyword.trim() !== '') {
						params.festivalname = keyword.trim();
					}

					$.ajax({
						url: url,
						type: 'GET',
						data: params,
						dataType: 'json',
						success: function(res) {
							layer.closeAll('loading');
							if (res.code === 200) {
								renderFestivalList(res.data.festivalPageInfo.list || []);
								renderPagination(res.data.festivalPageInfo.total, page || currentPage);
							} else {
								layer.msg(res.msgerr || '获取节日列表失败', {
									icon: 2
								});
							}
						},
						error: function(xhr) {
							layer.closeAll('loading');
							var errorMsg = '加载节日列表失败';
							try {
								var errRes = JSON.parse(xhr.responseText);
								errorMsg = errRes.msgerr || errorMsg;
							} catch (e) {}
							layer.msg(errorMsg, {
								icon: 2
							});
						}
					});
				}

				// 渲染节日列表
				function renderFestivalList(festivals) {
					var html = '';
					festivals.forEach(function(festival) {
						var discountInfo = festival.discountname ?
							`<span class="discount-tag">${festival.discountname}</span>` : '--';

						html += `
                        <tr>
                            <td>${festival.festivalid || '--'}</td>
                            <td>${festival.festivalname || '--'}</td>
                            <td>${formatDate(festival.festivalstart) || '--'}</td>
                            <td>${formatDate(festival.festivalend) || '--'}</td>
                            <td>
                                <img src="${festival.festivalimg || '../img/default-image.png'}"
                                    class="festival-icon-preview"
                                    onerror="this.src='../img/default-image.png'">
                            </td>
                            <td>${discountInfo}</td>
                            <td>
                                <div class="festival-actions">
                                    <button class="action-btn edit-festival" data-id="${festival.festivalid}">
                                        <i class="layui-icon" style="font-size: 14px;">&#xe642;</i> 编辑
                                    </button>
                                    <button class="action-btn delete-festival" data-id="${festival.festivalid}">
                                        <i class="layui-icon" style="font-size: 14px;">&#xe640;</i> 删除
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
					});
					$('#festivalTable tbody').html(html);

					// 绑定事件
					$('.edit-festival').on('click', function() {
						editFestival($(this).data('id'));
					});

					$('.delete-festival').on('click', function() {
						deleteFestival($(this).data('id'));
					});
				}

				// 日期格式化
				function formatDate(dateStr) {
					if (!dateStr) return '';
					return dateStr.split('T')[0];
				}

				// 渲染分页
				function renderPagination(total) {
					laypage.render({
						elem: 'pagination',
						count: total,
						curr: currentPage,
						limit: pageSize,
						layout: ['count', 'prev', 'page', 'next', 'skip'],
						jump: function(obj, first) {
							if (!first) {
								currentPage = obj.curr;
								loadFestivals();
							}
						}
					});
				}

				// 新增节日
				$('#addFestival').on('click', function() {
					resetForm();
					// 新增：不传参数，默认不选中任何优惠券
					loadDiscountOptions();
					layer.open({
						type: 1,
						title: '新增节日',
						area: ['700px', '550px'],
						content: $('#festivalDialog'),
						btn: ['确定', '取消'],
						yes: function(index) {
							submitForm(index);
						}
					});
					showDiscountArea();
				});

				// 编辑节日
				function editFestival(festivalId) {
					layer.load(1);
					// 存储当前编辑的活动ID
					currentEditFestivalId = festivalId;

					$.ajax({
						url: baseUrl + '/' + festivalId,
						type: 'GET',
						success: function(res) {
							layer.closeAll('loading');
							if (res.code === 200 && res.data) {
								var festival = res.data;
								console.log("编辑时获取到的数据festival");
								console.log(festival)
								// 存储当前活动关联的优惠券ID
								currentDiscountId = festival.discountid;


								// 填充表单
								form.val('festivalForm', {
									festivalid: festival.festivalid,
									festivalname: festival.festivalname,
									festivalstart: formatDate(festival.festivalstart),
									festivalend: formatDate(festival.festivalend),
									bless: festival.bless,
									discountid: festival.discountid
								});

								// 显示图片
								if (festival.festivalimg) {
									$('#previewImg').attr('src', festival.festivalimg).show();
									uploadStatus.imageUrl = festival.festivalimg;
									uploadStatus.isUploaded = true;
								}

								// 加载优惠券选项并传入当前优惠券ID实现自动选中
								loadDiscountOptions(currentDiscountId);

								// 打开编辑对话框
								layer.open({
									type: 1,
									title: '编辑节日',
									area: ['700px', '550px'],
									content: $('#festivalDialog'),
									btn: ['保存', '取消'],
									yes: function(index) {
										submitForm(index);
									},
									success: function() {
										$('#discountSelect').prop('disabled', false);
										form.render('select');
									}
								});
								hideDiscountArea();
							} else {
								layer.msg(res.msgerr || '获取节日信息失败', {
									icon: 2
								});
							}
						},
						error: function() {
							layer.closeAll('loading');
							layer.msg('获取节日信息失败', {
								icon: 2
							});
						}
					});
				}

				// 提交表单
				function submitForm(dialogIndex) {
					var formData = form.val('festivalForm');

					// 验证必填字段
					if (!formData.festivalname) {
						layer.msg('请输入节日名称', {
							icon: 2
						});
						return;
					}

					if (!formData.festivalstart) {
						layer.msg('请选择开始时间', {
							icon: 2
						});
						return;
					}

					if (!formData.festivalend) {
						layer.msg('请选择结束时间', {
							icon: 2
						});
						return;
					}

					if (!formData.festivalid && !uploadStatus.isUploaded) {
						layer.msg('请上传节日图片', {
							icon: 2
						});
						return;
					}

					// 检查时间有效性
					if (new Date(formData.festivalstart) > new Date(formData.festivalend)) {
						layer.msg('开始时间不能晚于结束时间', {
							icon: 2
						});
						return;
					}

					// 添加图片URL
					if (uploadStatus.isUploaded) {
						formData.festivalimg = uploadStatus.imageUrl;
					}

					// 确定请求URL
					var url = formData.festivalid ?
						baseUrl + '/updateFestivalendSky' :
						baseUrl + '/insertFestivalSky';

					// 提交数据
					layer.load(1);
					$.ajax({
						url: url,
						type: 'POST',
						contentType: 'application/json',
						data: JSON.stringify(formData),
						success: function(res) {
							layer.closeAll('loading');
							if (res.code === 200) {
								layer.msg(res.msgerr || '操作成功', {
									icon: 1
								});
								layer.close(dialogIndex);
								loadFestivals();
								resetForm();
							} else {
								layer.msg(res.msgerr || '操作失败', {
									icon: 2
								});
							}
						},
						error: function() {
							layer.closeAll('loading');
							layer.msg('请求失败，请稍后重试', {
								icon: 2
							});
						}
					});
				}

				// 删除节日
				function deleteFestival(festivalid) {
					layer.confirm('确定要删除这个节日吗？', {
						icon: 3,
						title: '提示'
					}, function(index) {
						layer.load(1);
						$.ajax({
							url: baseUrl + '/' + festivalid,
							type: 'DELETE',
							dataType: 'json',
							success: function(res) {
								layer.closeAll('loading');

								var success = false;
								var message = '删除失败';

								if (res && typeof res === 'object') {
									if (res.code === 200) {
										if (typeof res.data === 'number' && res.data > 0) {
											success = true;
											message = '删除成功';
										} else if (res.message === "删除成功" || res.msgerr === "删除成功") {
											success = true;
											message = '删除成功';
										}
									}

									if (res.message) {
										message = res.message;
									} else if (res.msgerr) {
										message = res.msgerr;
									}
								}

								if (success) {
									layer.msg(message, {
										icon: 1,
										time: 1500
									}, function() {
										loadFestivals();
									});
								} else {
									layer.msg(message, {
										icon: 2
									});
								}
							},
							error: function(xhr) {
								layer.closeAll('loading');
								var errorMsg = '删除请求失败';
								try {
									var errRes = JSON.parse(xhr.responseText);
									errorMsg = errRes.message || errRes.msgerr || errorMsg;
								} catch (e) {}
								layer.msg(errorMsg, {
									icon: 2
								});
							}
						});
					});
				}

				// 重置表单
				function resetForm() {
					form.val('festivalForm', {
						festivalid: '',
						festivalname: '',
						festivalstart: '',
						festivalend: '',
						bless: '',
						discountid: ''
					});
					$('#previewImg').attr('src', '').hide();
					$('#discountSelect').prop('disabled', false);
					uploadStatus = {
						isUploaded: false,
						imageUrl: ''
					};
					// 重置编辑状态变量
					currentEditFestivalId = null;
					currentDiscountId = null;
				}

				// 搜索节日
				$('#searchBtn').on('click', function() {
					var keyword = $('#searchInput').val().trim();
					currentPage = 1;
					loadFestivals(currentPage, keyword);
				});

				// 刷新
				$('#refreshBtn').on('click', function() {
					$('#searchInput').val('');
					searchKeyword = '';
					currentPage = 1;
					loadFestivals();
				});

				// 初始化加载数据
				loadFestivals();
			});

</script>
	</body>
</html>